<?php

class Score_NormalController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function errorAction()
    {

    }
    public function indexAction()
    {
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        $year = $this->view->Semester['year'];
        $semester = $this->view->Semester['semester'];

        // 取任教班級科目
        // TODO 分組班科目加入選單中
        $model = new Semester_Model_SemesterTeacherCourse();
        $teacherCourse = $model->getTeacherCourse($year,$semester,$teacherSn,Semester_Model_SemesterTeacherCourse::SCORED);

        if (count($teacherCourse) ==0)
        $this->_redirect('score/stage/yet-assign');

        $this->view->teacherCourse = $teacherCourse;
        $sn = $this->getRequest()->getPost('sn');
        if (!$sn)
        $sn =  current(array_keys($teacherCourse));
     // 檢查 sn 查否在本學期配課中
        elseif (!in_array($sn, array_keys($teacherCourse)) )
        {
            $this->_redirect('score/stage/error');
        }

        // 選擇配課科目流水號
        $this->view->sn = $sn ;
        // 目前輸入階段
        $stage = $this->getRequest()->getPost('stage_id');

        // 建立階段成績 object
        $scoreStage = new Score_Model_Normal($sn,$stage);


        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/normal/error');
        }

        // 評量階段數
        $this->view->period = $scoreStage->getExamine()->period;

        //目前輸入的階段
        $this->view->currStage = $scoreStage->getCurrStage();

        // 平時成績
        $this->view->scores = $scoreStage->getScores();

        // 平時成績平均
        if ($this->view->scores)
        $this->view->scoreAvg = $scoreStage->getScoreAverage();

        // 是否傳送成績
        $this->view->sendmit = $scoreStage->getSendmit();

        // 本學期學生名冊
        $this->view->students = $scoreStage->getStudents();

    }


    /**
     *  輸入成績
     * @return unknown_type
     */
    public function inputAction()
    {
        $this->getHelper ( 'layout' )->disableLayout ();
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        //        $year = $this->view->Semester['year'];
        //        $semester = $this->view->Semester['semester'];
        $sn =  $this->getRequest()->getPost('sn');
        $stage = (int)$this->getRequest()->getPost('stage_id');
        $this->view->sn = $sn;
        $this->view->stage = $stage;

        // 建立階段成績 object
        $scoreStage = new Score_Model_Normal($sn, $stage);
        //echo $teacherSn .'--'.$scoreStage->getTeacherCourse()->teacher_sn;
        //print_r($scoreStage->getTeacherCourse());
        //exit;
        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/normal/error');
        }

        $testOrder = (int)$this->getRequest()->getPost('test_order');
        // 修改,取回舊資料
        if ($testOrder) {
            $tempArr = $scoreStage->getScores($testOrder);
            $this->view->scores = $tempArr[$testOrder]['score'];
            $this->view->testName = $tempArr[$testOrder]['test_name'];
            $this->view->weighted = $tempArr[$testOrder]['weighted'];
            $this->view->test_order = $testOrder;
        } else {
            // 測驗名稱
            $this->view->testName  = $scoreStage->getSubjectSet()->subject_name. '- '.$scoreStage->getNextOrder();
            // 測驗加權
            $this->view->weighted  =1;
        }
        //
        // 本學期學生名冊

        $this->view->students = $scoreStage->getStudents();

    }

    /**
     * 登錄成績
     * @return unknown_type
     */
    public function signAction()
    {
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        $sn =  $this->getRequest()->getPost('sn');
        $stage = (int)$this->getRequest()->getPost('stage');

        // 建立階段成績 object
        $scoreStage = new Score_Model_Normal($sn,$stage);

        // 檢查是否為自己的配課,或已經傳送至教務處
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn or $scoreStage->getSendmit()=='Y') {
            $this->_redirect('score/normal/error');
        }

        $scores = $this->getRequest()->getPost('score');
        // 如果全部未輸入則離開
        $flag = false;
        foreach(array_values($scores) as $val) {
            if ($val !== ''){
                $flag = true;
                break;
            }
        }

        if ($flag) {
            $studentScoreNormal = new Student_Model_StudentScoreNormal();
            $fiter = new Zend_Filter_StripTags();
            if (!$testOrder = (int)$this->getRequest()->getPost('test_order'))
            $testOrder = $scoreStage->getNextOrder();

            if (!$scoreStage->isElective()) {
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Student_Model_StudentScoreNormal')
                ->where('class_sn=?', $scoreStage->getTeacherCourse()->class_sn)
                ->andWhere('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
                ->andWhere('test_sort=?', $stage)
                ->andWhere('test_order=?', $testOrder);
                $res = $q->fetchOne();
                if ($res) {
                    $normalSn = $res->sn;
                    $studentScoreNormal->assignIdentifier($normalSn);
                }
                $studentScoreNormal->class_sn = $scoreStage->getTeacherCourse()->class_sn;
                $studentScoreNormal->subject_sn = $scoreStage->getTeacherCourse()->subject_sn;
                $studentScoreNormal->test_sort = $stage;
                $studentScoreNormal->test_order = $testOrder;
                $studentScoreNormal->test_name = $fiter->filter($this->getRequest()->getPost('test_name'));
                $studentScoreNormal->weighted = (int)$this->getRequest()->getPost('weighted');
                $studentScoreNormal->teacher_sn = $teacherSn;
                $studentScoreNormal->save();
                $normalSn = $studentScoreNormal->sn;
            }



            foreach($scores as $studentSn=>$score) {
                if ($scoreStage->isElective()) {
                    $tempArr = explode("-",$studentSn);
                    $studentSn = (int)$tempArr[1];
                    // 分組班學生來自各班,須逐一學生查詢 student_score_stage 的 sn
                    // 如是未建立,則新增,
                    $q = Doctrine_Query::create()
                    ->select('sn')
                    ->from('Student_Model_StudentScoreNormal')
                    ->where('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
                    ->andWhere('class_sn=?', $tempArr[0])
                    ->andWhere('test_order=?', $testOrder)
                    ->andWhere('test_sort=?', $stage);
                    $res = $q->fetchOne();
                    $studentScoreNormal = new Student_Model_StudentScoreNormal();
                    if ($res) {
                        $normalSn = $res->sn;
                        $studentScoreNormal->assignIdentifier($normalSn);
                    }

                    $studentScoreNormal->subject_sn = $scoreStage->getTeacherCourse()->subject_sn;
                    $studentScoreNormal->class_sn = $tempArr[0];
                    $studentScoreNormal->test_order = $testOrder;
                    $studentScoreNormal->test_sort = $stage;
                    $studentScoreNormal->test_name = $fiter->filter($this->getRequest()->getPost('test_name'));
                    $studentScoreNormal->weighted = (int)$this->getRequest()->getPost('weighted');
                    // $studentScoreStage->teacher_sn = $teacherSn;
                    $studentScoreNormal->save();
                    $normalSn = $studentScoreNormal->sn;
                }


                if ($score!=='') {
                    $studentScoreNormalDetail = new Student_Model_StudentScoreNormalDetail();
                    $res = $studentScoreNormalDetail->getTable()
                    ->findBySql("normal_sn=? AND student_sn=?",array($normalSn,$studentSn))
                    ->getFirst();
                    if ($res)
                    $studentScoreNormalDetail->assignIdentifier($res->sn);

                    $studentScoreNormalDetail->normal_sn = $normalSn;
                    $studentScoreNormalDetail->student_sn = (int)$studentSn;
                    $studentScoreNormalDetail->score = (float) $score;
                    $studentScoreNormalDetail->teacher_sn = $teacherSn;
                    $studentScoreNormalDetail->save();
                }
            }
        }
        $this->_helper->json('ok');
    }

    /**
     * 刪除一項平時成績
     * @return unknown_type
     */
    public function deleteAction()
    {
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        $sn = $this->getRequest()->getParam('sn');
        $stage = (int)$this->getRequest()->getParam('stage_id');
        $testOrder = (int)$this->getRequest()->getParam('test_order');

        // 建立階段成績 object
        $scoreStage = new Score_Model_Normal($sn,$stage);

        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/normal/error');
        }
        $q = Doctrine_Query::create()
        ->delete('Student_Model_StudentScoreNormal');
        if (!$scoreStage->isElective())
        $q->where('class_sn=?', $scoreStage->getTeacherCourse()->class_sn);

        $q->andWhere('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
        ->andWhere('test_sort=?', $stage)
        ->andWhere('test_order=?', $testOrder);
        //        echo $q->getSqlQuery();
        $q->execute();

        $this->_helper->json(1);
    }

    /**
     * 匯出到階段成績
     * @return unknown_type
     */
    public function exportAction()
    {
        // 教師 sn
        $teacherSn = Teacher_Model_Teacher::getSnById();
        $sn = $this->getRequest()->getPost('sn');
        $stage = (int)$this->getRequest()->getPost('stage_id');

        // 建立階段成績 object
        $scoreStage = new Score_Model_Normal($sn,$stage);

        // 檢查是否為自己的配課
        if ($teacherSn != $scoreStage->getTeacherCourse()->teacher_sn) {
            $this->_redirect('score/normal/error');
        }
        // 非 分組課程
        if (! $scoreStage->isElective()) {
            // 查詢階段成績 sn
            $q = Doctrine_Query::create()
            ->select('sn')
            ->from('Student_Model_StudentScoreStage')
            ->where('class_sn=?', $scoreStage->getTeacherCourse()->class_sn)
            ->andWhere('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
            ->andWhere('test_sort=?', $stage);
            if ($stage ==  Score_Model_Stage::WHOLE_STAGE_SCORE)  //全學期
            $q->andWhere('test_kind=3');
            else
            $q->andWhere('test_kind=2'); // 平時成績

            $res = $q->fetchOne();

            if ($res) {
                $stageSn = $res->sn;
            }
            else { // 如未建立新增
                $studentScoreStage = new Student_Model_StudentScoreStage();
                $studentScoreStage->class_sn = $scoreStage->getTeacherCourse()->class_sn;
                $studentScoreStage->subject_sn = $scoreStage->getTeacherCourse()->subject_sn;
                if ($stage ==  Score_Model_Stage::WHOLE_STAGE_SCORE)
                $studentScoreStage->test_kind = 3;
                else
                $studentScoreStage->test_kind = 2;
                $studentScoreStage->test_sort = $stage;
                $studentScoreStage->teacher_sn = $teacherSn;
                $studentScoreStage->save();
                $stageSn = $studentScoreStage->sn;

            }
        }
        // 平時成績平均
        $scoreAverage = $scoreStage->getScoreAverage();

        foreach ($scoreAverage as $studentSn => $score) {
            // 分組班課程
            if ($scoreStage->isElective()) {
                $tempArr = explode("-",$studentSn);
                $studentSn = (int)$tempArr[1];
                // 分組班學生來自各班,須逐一學生查詢 student_score_stage 的 sn
                // 如是未建立,則新增,
                $q = Doctrine_Query::create()
                ->select('sn')
                ->from('Student_Model_StudentScoreStage')
                ->where('subject_sn=?', $scoreStage->getTeacherCourse()->subject_sn)
                ->andWhere('class_sn=?', $tempArr[0])
                ->andWhere('test_sort=?', $stage);
                if ($stage ==  Score_Model_Stage::WHOLE_STAGE_SCORE)  //全學期
                $q->andWhere('test_kind=3');
                else
                $q->andWhere('test_kind=2'); // 平時成績
                $res = $q->fetchOne();

                if ($res) {
                    $stageSn = $res->sn;
                }
                else { // 如未建立新增
                    $studentScoreStage = new Student_Model_StudentScoreStage();
                    $studentScoreStage->class_sn = $scoreStage->getTeacherCourse()->class_sn;
                    $studentScoreStage->subject_sn = $scoreStage->getTeacherCourse()->subject_sn;
                    if ($stage ==  Score_Model_Stage::WHOLE_STAGE_SCORE)
                    $studentScoreStage->test_kind = 3;
                    else
                    $studentScoreStage->test_kind = 2;
                    $studentScoreStage->test_sort = $stage;
                    //$studentScoreStage->teacher_sn = $teacherSn;
                    $studentScoreStage->save();
                    $stageSn = $studentScoreStage->sn;
                }
            }

            $q = Doctrine_Query::create()
            ->select('sn')
            ->from('Student_Model_StudentScoreStageDetail')
            ->where('stage_sn=?',$stageSn)
            ->andWhere('student_sn=?', $studentSn);
            $res =  $q->fetchOne();
            $studentScoreStageDetail = new Student_Model_StudentScoreStageDetail();
            if ($res)
            $studentScoreStageDetail->assignIdentifier($res->sn);

            $studentScoreStageDetail->student_sn = $studentSn;
            $studentScoreStageDetail->teacher_sn = $teacherSn;
            $studentScoreStageDetail->score = $score;
            $studentScoreStageDetail->stage_sn = $stageSn;
            $studentScoreStageDetail->save();
        }
        $this->_redirect('score/stage/index/sn/'.$sn);
    }
}

